<template>
  <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px">
    <el-timeline>
      <el-timeline-item v-for="(item, index) in milepostList" :key="index + 'competitor'" color="#0A6ED2" style="margin-bottom: 20px;">
        {{ '里程碑及任务' + (index + 1) }}
        <el-row>
          <el-col :span="12">
            <el-form-item :label="'里程碑及任务名称'" :rules="rules.validateRequire">
              <el-input v-model="item.milepostname" :disabled="disableMilepostNameByType(item)" :class="{ 'copy-edit-tip' : (item.copyedit && item.copyedit === '0' && item.sourceid === 0) }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划达成日期" :rules="rules.validateRequire">
              <el-date-picker v-model="item.planfinishtime" type="date" @change="selectTime(index, item.planfinishtime)" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" :disabled="item.enabled === 1 || item.milepoststate === 1 || isshowdisable"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="责任人" :rules="rules.validateRequire">
              <!-- <el-input v-model="item.responsible" :disabled="true" class="tl-ref-selector">
                <el-button slot="append" type="primary" icon="el-icon-search" @click="openmpmProjectTeamRefDialog(index)" :disabled="item.newadd === 0"></el-button>
              </el-input> -->
              <tl-mpm-project-stakeholder-ref :initDisplayData.sync="item.responsible" :externalSelectedRowKeys="item.responsiblecode" @confirm="addConfirm(index, arguments)" title="责任人" :externalQueryParam="externalQueryParam" :isSingleSelect="true" :disabled="item.enabled === 1 || item.milepoststate === 1 || isshowdisable"></tl-mpm-project-stakeholder-ref>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交付成果" :rules="rules.validateRequire">
              <el-input v-model="item.deliverable" :disabled="item.enabled === 1 || item.milepoststate === 1 || isshowdisable" :class="{ 'copy-edit-tip' : (item.copyedit && item.copyedit === '0') }"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序码">
              <el-input-number v-model="item.sortcode" controls-position="right" :step="1" :min="0" style="width:100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <tl-index-Task style="margin-left: 120px;" :disabled="isshowdisable" :index="index" ref="task" :milepost="item" :milepostname="item.milepostname" :milepostcode="item.operatecode" :projectinfo="projectinfo" :planstate="planstate" :customerTaskFlag="customerTaskFlag"  @refresh="refreshForState" :provincePmChangeFlag="provincePmChangeFlag"></tl-index-Task>
        <el-col :span="8">
          <el-button type="text" v-if="(item.enableDelete || item.newadd !== 0 || provincePmChangeFlag) && !isshowdisable" style="margin-left:140px" @click="removeCompetitor(item, index)">删除里程碑及任务</el-button>
        </el-col>
      </el-timeline-item>
    </el-timeline>
    <el-row v-if="!isshowdisable">
      <el-col :span="24">
        <el-button type="text" @click="addCompetitor" icon="el-icon-circle-plus-outline" style="margin-left:140px">新增里程碑及任务</el-button>
        <el-button class="filter-item" v-if="ifShowTemplateAdd" type="text" icon="el-icon-circle-plus-outline" @click="openAddDialog('editTemplateForm')">按模板新增</el-button>
        <el-button class="filter-item" type="text" icon="el-icon-circle-plus-outline" @click="openProjectRef()">按历史项目新增</el-button>
      </el-col>
    </el-row>
    <!-- <tlmpm-project-stakeholde-ref ref="mpmProjectTeamRef" @confirm="getMpmProjectTeamData" :externalQueryParam="externalQueryParamForPool"></tlmpm-project-stakeholde-ref> -->
    <tlmpm-project-team-ref ref="mpmProjectTeamRef" @confirm="getMpmProjectTeamData" :externalQueryParam="externalQueryParamForPool"></tlmpm-project-team-ref>
    <tl-edit-template ref="editTemplateForm" @refresh="doRefresh" :parentId="parentId" :projectinfo="projectinfo" :isSingleSelect="false"></tl-edit-template>
    <tl-edit-project ref="editProjectForm" @refresh="doRefresh" :parentId="parentId" :projectinfo="projectinfo"></tl-edit-project>
    <project-plan-tree-ref ref="projectPlanTreeRef" :projectInfo="projectinfo" :planId="parentId" @refreshData="refreshData"></project-plan-tree-ref>
    <tl-import-excel v-show="false" ref="importRef" :uploadUrl="url.importExcel" tableName="MpmProjectMilepost" @beginUpload="saveLoadingStart" @endUpload="saveLoadingEnd" :parentId="parentId" :projectcode="projectinfo.projectcode" @refresh="refreshExcel"></tl-import-excel>
  </el-form>
</template>

<script>
/** mixins */
import { mixin_edit } from '@tapui/mixins/mixin_edit'

/** 子组件 */
import TlMpmProjectStakeholderRef from '../mpmProjectStakeholder/refList'
import tlmpmProjectTeamRef from '@/views/mpm/mpmProjectTeam/refList'
import tlIndexTask from './indexTask'
import tlEditTemplate from './editTemplate'
import tlEditProject from './editProject'
import projectPlanTreeRef from '@/components/common/ProjectPlanTreeRef'
import tlImportExcel from './importExcel'
import { validateNull } from '@tapui/utils/validate'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { MPM_TASK_TEMPLATE_TYPE } from '@/const/const'
import { formatDate } from '@tapui/utils/date'
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { tlmpmProjectTeamRef, tlIndexTask, tlEditTemplate, tlEditProject, TlMpmProjectStakeholderRef, projectPlanTreeRef, tlImportExcel },
  data() {
    return {
      moduleTitle: '项目策划-里程碑及任务',
      urlPrefix: '/mpm/projectMilepost/',
      externalQueryParamForPool: {},
      url: {
        // 额外的url
        milepostLoadInfo: '/mpm/projectMilepost/milepostLoadInfo',
        updateInfo: '/mpm/projectMilepost/updateInfo',
        saveMilepost: '/mpm/projectMilepost/saveMilepost',
        updateMilepostBatch: '/mpm/projectMilepost/updateMilepostBatch',
        importExcel: '/mpm/projectMilepost/importExcel'
      },
      milepostList: [],
      milepostIndex: -1,
      // 人员组件查询参数
      externalQueryParam: {
        qry_projectcode: this.projectinfo.projectcode // 项目编号
      },
      downLoading: false
    }
  },
  props: {
    parentId: {
      type: [Number, String],
      default: ''
    },
    operatecode: {
      type: String
    },
    projectinfo: {},
    planstate: {
      type: [Number, String],
      default: ''
    },
    isshowdisable: {
      type: Boolean,
      default: false
    },
    customerTaskFlag: {
      type: Boolean,
      default: false
    },
    provincePmChangeFlag: {
      type: Boolean,
      default: false
    },
    ifFistPlan: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ifShowTemplateAdd() {
      if ((this.projectinfo.projectlevel === '0' || this.projectinfo.projectlevel === '1') && (this.projectinfo.purchasepattern === '11' || this.projectinfo.purchasepattern === '12' || this.projectinfo.purchasepattern === '13')) {
         // 只有A级或B级的招标项目才显示
        return true
      } else {
        return false
      }
    },
    disableMilepostNameByType() {
      return (item) => {
        let templateTypeList = [MPM_TASK_TEMPLATE_TYPE.bidGuide, MPM_TASK_TEMPLATE_TYPE.LtcNew]
        return item.enabled === 1 || templateTypeList.includes(item.templatetype) || item.milepoststate === 1 || this.isshowdisable
      }
    }
  },
  methods: {
    // 开始等待
    saveLoadingStart() {
      this.downLoading = true
    },
    // 结束等待状态
    saveLoadingEnd() {
      this.downLoading = false
    },
    // 里程碑及任务计划达成日期与任务计划完成时间校验（用于策划提交审批前调用）
    checkTime(index, time) {
      let canapprove = true
      let taskplanenddate = this.$refs.task[index].datas.filter(item => {
        return item.planenddate !== null && item.planenddate !== undefined
      })
      taskplanenddate.some(item => {
        if (new Date(time) < new Date(item.planenddate)) {
          this.$tap.alert("里程碑及任务的计划达成时间不能早于任务的计划达成时间！")
          canapprove = false
          return
        }
      })
      return canapprove
    },
    // 当更新了项目状态时回调
    refreshForState() {
      this.$emit('refresh')
    },
    updatemilepostBatch() {
      postAction(this.url.updateMilepostBatch, { milepostList: this.milepostList }).then((res) => {
        if (res.success) {
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 人员选择后赋值
    addConfirm(index, ...values) {
      this.$set(this.milepostList[index], 'responsiblecode', values[0][1])
      this.$set(this.milepostList[index], 'responsible', values[0][2])
      this.$set(this.milepostList[index], 'projectcode', this.projectinfo.projectcode)
    },
    async updateInfo() {
        return await postAction(this.url.updateInfo, { milepostList: this.milepostList, projectcode: this.projectinfo.projectcode, planid: this.parentId }).then((res) => {
          if (res.success) {
            // this.$refs.line.milepostLoadInfo()
          } else {
            this.$tap.alert(res.message, 'warning')
            return Promise.reject(new Error(res.message))
          }
        })
    },
    selectTime(index, time) {
      if (this.formatDateToMicro(time) > this.formatDateToMicro(this.projectinfo.planenddate)) {
        this.$tap.alert('里程碑及任务的计划达成时间不能晚于所属项目的计划结束时间！')
        this.milepostList[index].planfinishtime = null
        return
      }
      if (this.formatDateToMicro(time) < this.formatDateToMicro(this.projectinfo.planstartdate)) {
        this.$tap.alert('里程碑及任务的计划达成时间不能早于所属项目的计划开始时间！')
        this.milepostList[index].planfinishtime = null
        return
      }
      let taskplanenddate = this.$refs.task[index].datas.filter((item) => {
        return item.planenddate !== null && item.planenddate !== undefined
      })
      taskplanenddate.forEach((item) => {
        if (this.formatDateToMicro(time) < this.formatDateToMicro(item.planenddate)) {
          this.$tap.alert('里程碑及任务的计划达成时间不能早于任务的计划达成时间！')
          this.milepostList[index].planfinishtime = null
          return
        }
      })
    },
    /** 打开新增对话框实现 */
    openAddDialog(editForm, rowData) {
      this.$refs[editForm].isAdd = true
      this.$refs[editForm].visible = true
      this.$refs[editForm].disableEditSubmit = false
      this.$refs[editForm].addFromPlan = true
    },
    removeCompetitor(item, index) {
      const that = this
      this.$tap
        .confirm('确定删除里程碑及里程碑下所有任务吗？')
        .then((_) => {
          // if (item.templatetype === undefined || item.templatetype !== "1") {
          //   if (this.$refs.task[index].datas.length > 0) {
          //     this.$tap.alert("已关联任务，不允许删除！")
          //     return
          //   }
          // }
          deleteAction('/mpm/projectMilepost/delete', { ids: item.id }).then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.$refs.form.clearValidate()
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
          that.milepostList.splice(index, 1)
        })
        .catch((_) => {})
    },
    saveMilepost(index) {
      postAction(this.url.saveMilepost, { milepost: this.milepostList[index], projectcode: this.projectinfo.projectcode, planid: this.parentId }).then((res) => {
        if (res.success) {
          this.$refs.form.clearValidate()
          if (res.result.operatecode) {
            this.$set(this.milepostList[index], 'operatecode', res.result.operatecode)
            this.$set(this.milepostList[index], 'milepostcode', res.result.milepostcode)
            this.$set(this.milepostList[index], 'milepoststate', res.result.milepoststate)
            this.$set(this.milepostList[index], 'id', res.result.id)
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    addCompetitor() {
      this.milepostList.push({ sortcode: 0 })
      this.saveMilepost(this.milepostList.length - 1)
    },
    // userConfirm(selectData) {
    //   const selectedUser = selectData[0]
    //   const { code, name } = selectedUser
    //   this.$set(this.model, "responsiblecode", code)
    //   this.$set(this.model, "responsible", name)
    //   this.$set(this.model, "projectcode", this.projectinfo.projectcode)
    // },
    loaded() {
      // 页面加载完毕执行
      if (this.isAdd) {
        this.$set(this.model, 'planid', this.parentId)
      }
      this.milepostLoadInfo()
    },
    async milepostLoadInfo() {
      if (this.parentId !== '') {
        return await getAction(this.url.milepostLoadInfo, { id: this.parentId }).then((res) => {
          if (res.success) {
            this.milepostList = res.result.milepostList
          } else {
            this.$tap.alert(res.message, 'warning')
            return Promise.reject(new Error(res.message))
          }
        })
      }
    },
    getMpmProjectTeamData(selectionRow, selectKey, selectionValue) {
      this.$set(this.milepostList[this.milepostIndex], 'responsiblecode', selectionRow.usercode)
      this.$set(this.milepostList[this.milepostIndex], 'responsible', selectionRow.username)
      this.$set(this.milepostList[this.milepostIndex], 'projectcode', this.projectinfo.projectcode)
    },
    openmpmProjectTeamRefDialog(index) {
      this.milepostIndex = index
      this.externalQueryParamForPool = {
        qry_projectcode: this.projectinfo.projectcode,
        qry_state: 9,
        qry_enabled: 1,
        qry_appointmenttype: 1
      }
      this.$refs.mpmProjectTeamRef.visible = true
    },
    doRefresh() {
      // this.$refs.task[task.length-1].doRefresh()
    },
    formatDateToMicro(date) {
      return new Date(formatDate(new Date(date), 'yyyy-MM-dd')).getTime()
    },
    /** 打开项目参照 **/
    openProjectRef() {
      this.$refs.projectPlanTreeRef.visible = true
    },
    /** 获取项目参照数据 */
    getMpmProjectData(selectionRow, selectKey, selectionValue) {
      this.$set(this.queryParam, 'qry_projectname', selectionRow.projectname)
      this.$set(this.queryParam, 'qry_projectcode', selectionRow.projectcode)
      this.loadData({})
    },
    refreshData() {
      this.milepostLoadInfo()
      this.$refs.projectPlanTreeRef.visible = false
    },
    // 如果存在里程碑，则需要提示导入会覆盖同名里程碑
    doexcelImport() {
      if (!validateNull(this.milepostList)) {
        if (this.ifFistPlan) {
          this.$tap.confirm('导入将覆盖同名里程碑，确定导入数据吗？').then((_) => {
            this.$refs.importRef.$refs.importRef1.$el.click()
          })
        } else {
          this.$tap.confirm('导入后会将现有里程碑、任务全部覆盖，请确认是否导入').then((_) => {
            this.$refs.importRef.$refs.importRef1.$el.click()
          })
        }
      } else {
          this.$refs.importRef.$refs.importRef1.$el.click()
      }
    },
    refreshExcel() {
      this.milepostLoadInfo()
    }
  },
  watch: {
    // 当projectInfo改变时，为externalQueryParam赋值
    projectinfo(newVal, oldVal) {
      this.externalQueryParam.qry_projectcode = newVal.projectcode
    }
  }
}
</script>
<style scoped>
  .copy-edit-tip /deep/ .el-input__inner {
    background-color: #ff8c2e!important;
    color: #000000;
  }
</style>
